package start.demo01.email;

import org.apache.commons.mail.*;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
public class SendEmail {
	/**
	 * mail-host=smtp.qq.com
	 * mail-from=790867216@qq.com
	 * mail-to=1091979637@qq.com
	 * mail-code=
	 */

	//发件服务器
	private static String mailHost="smtp.qq.com";
	//发件箱（人）
	private static String mailFrom="790867216@qq.com";
	//授权码（密码）:whesnkdbeajlbdia
//	private static String mailCode="whesnkdbeajlbdia";
	private static String mailCode="khmkygxoiexvbfgf";
	private static String mailTo="1091979637@qq.com";
	//
//	static {
//		try {
//			Properties prop = new Properties();
//			prop.load(SendEmail.class.getClassLoader().getResourceAsStream("mail.properties"));
//			mailHost = prop.getProperty("mail-host");
//			mailFrom = prop.getProperty("mail-from");
//			mailCode = prop.getProperty("mail-code");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
	public static void main(String[] args){
		sendSimpleEmail(null,"bug","布克思");
	}
	public static void sendSimpleEmail(String toAddress, String subject, String content) {
		try {
			Email email = new SimpleEmail();
			email.setHostName(mailHost);
			email.setSmtpPort(465);
			email.setAuthenticator(new DefaultAuthenticator(mailFrom, mailCode));
			email.setSSLOnConnect(true);
			email.setFrom(mailFrom);
			email.setSubject(subject);
			email.setMsg(content);
			email.addTo(mailTo);
			email.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}

	public static void sendHtmlFormattedMail(String subject, User user) {
		try {
			// Create the email message
			HtmlEmail email = new HtmlEmail();
			email.setHostName(mailHost);
			email.addTo(user.getEmail());
			email.setFrom(mailFrom);
			email.setAuthentication(mailFrom, mailCode);
			email.setSubject(subject);
			email.setCharset("UTF-8");
		
			// set the html message
			email.setHtmlMsg(readHtml(user));
			// send the email
			email.send();
		} catch (EmailException | IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取激活电子邮件的html模板
	 * @param user 用户信息
	 * @return 
	 * @throws IOException
	 */
	private static String readHtml(User user) throws IOException {
		InputStream in = SendEmail.class.getClassLoader().getResourceAsStream("mailContent.html");
		byte[] buffer = new byte[1024];
		int len = -1;
		String content = "";
		while((len = in.read(buffer)) != -1) {
			content += new String(buffer,0,len);
		}
		return content.replace("${user.username}", user.getUsername()).replace("${user.password}", user.getPassword());
	}
}
